<?php
declare (strict_types=1);

namespace app\common\listener;

use app\common\model\Relation;
use app\common\model\User;
use app\common\model\UserLevel;
use app\common\model\UserLevelFlag;
use app\common\model\UserLevelLog;
use think\Exception;
use think\facade\Event;
use think\facade\Log;

class UserDemotion
{
    /**
     * 会员等级降级
     * 店主以上级别需要每年续约，续约要在续约专区购买续约套餐即可。
     * 若未进行及时续约，级别掉为普通会员，不再享受任何权益，同时要扣除上三代盟主的推荐分，
     * 自身掉级会影响上级会员的级别，可能会引发连续掉级
     * @param $user
     * @throws Exception
     */
    public function handle($user)
    {
        try{
            if($user->syn_level < 3){//店主以下级别
                return false;
            }

            $this->log($user, $user->level_id, 1);

            //todo 上级会员连续掉级
            //todo 扣除上三代盟主的推荐分
            $high_min = UserLevel::where('id', 4)->value('shopers');
            Relation::with(['user'])->where('new_uid', $user->id)->field('id, uid, algebra')->select()
                ->each(function ($item) use ($user, $high_min){
                    if($item->user->level_id == 4){
                        $has_shopers = User::where(['parent_id'=> $item->user->id, 'is_del'=>0])->where('level_id', '>=', 3)->count();
                        if($has_shopers < $high_min){//由高级店主降为店主
                            $this->log($item->user, $user->level_id, 3);
                            $user->level_id = 3;
                            $user->syn_level = 3;
                            $user->save();
                        }
                    }elseif($item->user->level_id == 5){
                        $this->leader($item->user, $user->id);
                    }

                });
        }catch (\Exception $e){
            Log::write("listener.UserDemotion:".$e->getMessage());
            throw new Exception("加载失败：".$e->getMessage(), -1);
        }

        return true;
    }

    private function leader($user, $relation_uid): bool
    {
        $leader_min = UserLevel::where('id', 5)->value('shopers');
        $relations = Relation::three($user);//三代内
        $has_shopers = User::whereIn('id',$relations)->where('syn_level','>=',3)->count();
        if($has_shopers < $leader_min){//225配置：邀请店主及店主以上级别人数
            $this->log($user, $user->level_id, 4);
            $user->level_id = 4;
            $user->syn_level = 4;
            $user->save();

            return (new UserLevelFlag())->flag($user);
        }

        return false;
    }


    /**
     * 会员级别变更记录
     * @param $user
     * @param $before_level_id
     * @param $after_level_id
     * @param $relation_uid
     * @return bool
     */
    private function log($user, $before_level_id, $after_level_id, $relation_uid=0): bool
    {
        if($user->id == $relation_uid){
            $user->level_id = 1;
            $user->level_tag_id = 0;
            $user->level_bonus_id = 0;
            $user->save();
        }
        $param['relation_uid'] = $relation_uid;
        return UserLevelLog::levelLog($user,1,$before_level_id, $after_level_id,null,$param);
    }

}